﻿AB.namespace("INV_AddOrder.Mgr");
/// <summary>
/// 作者：姚少鹏
/// </summary>
INV_AddOrder.Mgr = {
    Insert: function () {
        DetailGridPanel.insertRecord(0, {});
        DetailGridPanel.startEditing(0, 0);
    },
    Add: function () {
        var rowIndex = DetailGridPanel.addRecord();
        DetailGridPanel.getView().focusRow(rowIndex);
        DetailGridPanel.startEditing(rowIndex, 0);
    },
    Delete: function () {
        DetailGridPanel.deleteSelected();
        DetailGridPanel.store.load(DetailGridPanel.store.lastOptions);
    },
    Clear: function () {
        DetailGridPanel.clear();
    },
    Save: function () {
        var FIdT = FIdH.getValue();
        var FNumberT = tfOrderNumber.getValue();
        var FCustomerId = cbCustomer.getValue();
        var FBillDate = dfDate.getValue();
      
        if (FBillDate == "") {
            Ext.Msg.show({
                title: '操作失败',
                msg: '请选择开单日期!',
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
            return;
        }

        var details = "";

        var isShortage = false;

        var dataSet = DetailGridPanel.getView().ds;
        if (dataSet != null) {
            var errorI = "";
            var errorPrice = "";
            var errorNumber = "";
            var items = dataSet.data.items;
            for (var i = 0; i < items.length; i++) {
                var FProductId = items[i].data.FProductId;
                if (FProductId == "") {
                    errorI += (i + 1) + ",";
                }

                var FPrice = items[i].data.FPrice;
                if (FPrice == "" ||FPrice <0) {
                    errorPrice += (i + 1) + ",";
                }

                var FNumber = items[i].data.FNumber;
                if (FNumber == "" || FNumber<=0) {
                    errorNumber += (i + 1) + ",";
                }

                details += "{FId:'" + items[i].data.FId
                + "',FProductId:'" + items[i].data.FProductId
                + "',FQty:'" + items[i].data.FQty
                + "',FNumber:'" + items[i].data.FNumber
                + "',FPrice:'" + items[i].data.FPrice
                + "',FAmount:'" + items[i].data.FAmount
                + "',FRemark:'" + items[i].data.FRemark
                + "'}";
                if (i < items.length - 1) {
                    details += ",";
                }

                if ((items[i].data.FQty > items[i].data.FProductInventoryQty) && isShortage == false) {
                    isShortage = true
                }
            }
            var errorMsg = "";
            if (errorI != "") {
                errorMsg = "第[" + errorI.substr(0, errorI.length - 1) + "]行产品编号无效！<br/>";
            }
            if (errorPrice != "") {
                errorMsg += "第[" + errorPrice.substr(0, errorPrice.length - 1) + "]行产品单价无效！<br/>";
            }
            if (errorNumber != "") {
                errorMsg += "第[" + errorNumber.substr(0, errorNumber.length - 1) + "]行产品数量无效！<br/>";
            }
            if (errorMsg != "") {
                showDetailMsg(MsgDF, errorMsg);
                return;
            }
        }

        if (isShortage) {
            Ext.Msg.confirm('提示', '存在产品数量已超过库存数量，还继续要保存吗?', function (btn) {
                if (btn == "yes") {
                    saveSendOrder(FIdT, FNumberT, FCustomerId, FBillDate, FNumberT, details, dataSet);
                }
            });
        } else {
            saveSendOrder(FIdT, FNumberT, FCustomerId, FBillDate, FNumberT, details, dataSet);
        }
    },
    Print: function () {
        var FId = FIdH.getValue();
        var SortDirectValue = SortDirect.Value;
        if (FId == "") {
            Ext.Msg.show({
                title: '操作失败',
                msg: '请先保存发货单!',
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
            return;
        }
        if (FSendOrderStatus.getValue() != "Approved") {
            Ext.Msg.show({
                title: '操作失败',
                msg: '请先确认发货单!',
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
            return;
        }
        var dataSet = DetailGridPanel.getView().ds;
        if (dataSet != null) {
            var errorAmount = "";
            var items = dataSet.data.items;
            for (var i = 0; i < items.length; i++) {
                var FAmount = items[i].data.FAmount;
                if (FAmount == "" || FAmount == "0" || FAmount == "0.00") {
                    errorAmount += (i + 1) + ",";
                }
            }
            var errorMsg = "";
            if (errorAmount != "") {
                errorMsg = "第[" + errorAmount.substr(0, errorAmount.length - 1) + "]行总额为零，请检查！<br/>";
            }
            if (errorMsg != "") {
                showDetailMsg(MsgDF, errorMsg);
                return;
            }
        }
        window.open("/SendOrder/ExportSendOrderToExcel?FId=" + FId + "&SortDirect=" + SortDirectValue);
    },
    getRowClass: function (record) {
        if (record.newRecord) {
            return "new-row";
        }
        if (record.dirty) {
            return "dirty-row";
        }
    },
    startEditing: function (e) {
        if (e.getKey() === e.ENTER) {
            var grid = DetailGridPanel;
            record = grid.getSelectionModel().getSelected();
            index = grid.store.indexOf(record);

            grid.startEditing(index, 1);
        }
    },
    afterEdit: function (e) {
        var grid = DetailGridPanel;
        var field = e.field;
        var valueOld = e.originalValue;
        var valueNew = e.value;
        var currentRow = e.row;
        var data = e.record.data;

        var priceType = cbProductPriceType.getRawValue();

        if (valueOld != valueNew) {
            if (field == "FProductNumber") {
                Ext.Ajax.request({
                    url: "/Product/GetProductMsgByFNumber",
                    method: 'post',
                    params: {
                        FNumber: valueNew,
                        priceType: priceType
                    },
                    success: function (result) {
                        if (!isTimeOut(result)) {
                            var response = Ext.util.JSON.decode(result.responseText);
                            if (response.success == false) {
                                ajaxFailureHandler(response);
                            } else {
                                if (response.extraParamsResponse.Result == "true") {
                                    grid.store.getAt(currentRow).set("FProductId", response.extraParamsResponse.FId);
                                    grid.store.getAt(currentRow).set("FProductName", response.extraParamsResponse.FName);
                                    grid.store.getAt(currentRow).set("FProductModelName", response.extraParamsResponse.FProductModelName);
                                    grid.store.getAt(currentRow).set("FProductInventoryQty", response.extraParamsResponse.FProductInventoryQty);
                                    grid.store.getAt(currentRow).set("FPrice", response.extraParamsResponse.FPrice);
                                    showDetailMsg(MsgDF, "");
                                } else {
                                    showDetailMsg(MsgDF, "输入产品编号无效！");
                                }
                            }
                        }
                    },
                    failure: failureHandler
                });
            }
            else if (field == "FQty") {
                var model = eval('(' + data.FProductModelName + ')');
                var number = valueNew * model;
                grid.store.getAt(currentRow).set("FNumber", number);

                var amount = number * data.FPrice;
                grid.store.getAt(currentRow).set("FAmount", amount);
            }
            else if (field == "FPrice") {
                var amount = valueNew * data.FNumber;
                grid.store.getAt(currentRow).set("FAmount", amount);
            }
            else if (field == "FNumber") {
                var model = eval('(' + data.FProductModelName + ')');
                if (valueNew >= 0 && model >0) {
                    grid.store.getAt(currentRow).set("FQty", Math.floor(valueNew / model));
                }
                var amount = valueNew * data.FPrice;
                grid.store.getAt(currentRow).set("FAmount", amount);
               
            }
        }
    },
    approveSendOrder: function () {
        var FIdT = FIdH.getValue();
        if (FIdT == "") {
            Ext.Msg.show({
                title: '操作失败',
                msg: '请先保存发货单!',
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
            return;
        }

        Ext.Msg.confirm('提示', '确定要确认该发货单吗?', function (btn) {
            if (btn == "yes") {
                Ext.Ajax.request({
                    url: "/SendOrder/ApproveSendOrder",
                    method: 'post',
                    params: {
                        FId: FIdT
                    },
                    success: function (result) {
                        if (!isTimeOut(result)) {
                            var response = Ext.util.JSON.decode(result.responseText);
                            if (response.success == false) {
                                ajaxFailureHandler(response);
                            } else {
                                var response = Ext.util.JSON.decode(result.responseText);
                                Ext.Msg.alert('操作信息', response.result);
                                FSendOrderStatus.setValue("Approved");
                            }
                        }
                    }
                });
            }
        });
    },
    createNewSendOrder: function () {
        FIdH.setValue("");
        tfOrderNumber.setValue("");
        cbCustomer.setValue("");
        dfDate.setValue(Ext.util.Format.date(new Date(), "Y/m/d"));
        FSendOrderStatus.setValue("");
        DetailGridPanel.clear();
        showDetailMsg(MsgDF, "新增送货单");
    }
}

var showDetailMsg = function (item, msg) {
    item.setValue(msg);
}

var saveSendOrder = function (FIdT, FNumberT, FCustomerId, FBillDate, FNumber, details, dataSet) {
    var msg = "{FId:'" + FIdT
        + "',FNumber:'" + FNumberT
        + "',FCustomerId:'" + FCustomerId
        + "',FBillDate:'" + Ext.util.Format.date(FBillDate, 'Y-m-d')
        + "',FNumber:'" + FNumber
        + "',FDetails:[" + details + "]}";

    Ext.Ajax.request({
        url: "/SendOrder/SaveSendOrderMsg",
        method: 'post',
        params: {
            msg: msg
        },
        success: function (result) {
            if (!isTimeOut(result)) {
                var response = Ext.util.JSON.decode(result.responseText);
                if (response.success == false) {
                    ajaxFailureHandler(response);
                } else {
                    var results = response.result.split("_");
                    FIdH.setValue(results[0]);
                    FSendOrderStatus.setValue("Saved");
                    tfOrderNumber.setValue(results[1]);
                    showDetailMsg(MsgDF, "订单保存成功！");
                    //var details = getSendOrderDetailJosnData(dataSet);
                    //OrderDetailListStore.loadData(details,true);
                }
            }
        }
    });
}

var getSendOrderDetailJosnData = function (dataSet) {
    var details = "{\"data\":[";
    var items = dataSet.data.items;
    for (var i = 0; i < items.length; i++) {
        details += "{\"FId\":\"" + items[i].data.FId
                + "\",\"FProductNumber\":\"" + items[i].data.FProductNumber
                + "\",\"FProductName\":\"" + items[i].data.FProductName
                + "\",\"FProductModelName\":\"" + items[i].data.FProductModelName
                + "\",\"FQty\":\"" + items[i].data.FQty
                + "\",\"FNumber\":\"" + items[i].data.FNumber
                + "\",\"FProductInventoryQty\":\"" + items[i].data.FProductInventoryQty
                + "\",\"FPrice\":\"" + items[i].data.FPrice
                + "\",\"FAmount\":\"" + items[i].data.FAmount
                + "\",\"FRemark\":\"" + items[i].data.FRemark
                + "\"}";
        if (i < items.length - 1) {
            details += ",";
        }
    }
    details += "], \"total\":\"" + items.length + "\"}";
    return details;

}